package com.tianzeculture.stagebao.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.renderscript.Allocation;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.tianzeculture.stagebao.application.StageBaoApplication;
import com.tianzeculture.stagebao.bean.JobBean;
import com.tianzeculture.stagebao.bean.User;
import com.tianzeculture.stagebao.bean.WorkTypeBean;
import com.tianzeculture.stagebao.network.util.ToastUtil;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.mob.MobSDK.getContext;

/**
 * Created by Administrator on 2018/5/28 0028.
 */

public class Util {


    //    public static String IMAGE_URL = "http://192.168.0.169:8081";//测试图片
    public static String IMAGE_URL = "http://47.106.116.243:8081";//线上图片

    public static String Token = "";
    public static String Uid = "";
    public static String UserId = "";
    public static String Rid = "";
    public static String AuthenticationStatus = "1";
    public static User user = null;

    public static List<JobBean> allJobBeen = null;//所有职业
    public static List<WorkTypeBean> allWorkTypeBeen = null;//所有工作类型


    public static final int CHOOSE_JOB = 101;//选择职业
    public static final int CHOOSE_NICKNAME = 102;//昵称
    public static final int WORK_TYPE = 103;//工作类型
    public static final int SELECT_CITY = 104;//选择城市
    public static final int HOT_TAG = 105;//热门标签
    public static final int WORK_TAG = 106;//工作标签
    public static final int TO_ADD_PHOTO = 107;//编辑图片页
    public static final int EDIT_ARTIST_BASIC = 108;//编辑艺人基本信息
    public static final int EDIT_ARTIST_PRICE = 109;//编辑艺人报价
    public static final int WORK_BREAKDOWN = 110;//编辑艺人报价
    public static final int WORK_EXPERIENCE = 111;//工作经验
    public static final int PAGE_SIZE = 10;//分页加载每页数量


    public static int JOB = 0;//0艺人 1商家
    public static String ALENT = "0";//1已加入 0未加入

    // 两次点击按钮之间的点击间隔不能少于1000毫秒
    private static final int MIN_CLICK_DELAY_TIME = 1000;
    private static long lastClickTime;

    /**
     * 重复点击处理
     *
     * @return
     */
    public static boolean isFastClick() {
        boolean flag = false;
        long curClickTime = System.currentTimeMillis();
        if ((curClickTime - lastClickTime) >= MIN_CLICK_DELAY_TIME) {
            flag = true;
        }
        lastClickTime = curClickTime;
        return flag;
    }

    /**
     * 关闭软键盘
     *
     * @param activity
     */
    public static void closeKeyboard(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }


    /**
     * 验证手机号码合法性
     *
     * @param phone
     * @return
     */
    public static boolean isPhone(String phone) {
        String regex = "^((13[0-9])|(14[5,7,9])|(15([0-3]|[5-9]))|(17[0,1,3,5,6,7,8])|(18[0-9])|(19[8|9]))\\d{8}$";
        if (phone.length() != 11) {
            ToastUtil.showShort(StageBaoApplication.getInstance(), "手机号应为11位数");
            return false;
        } else {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            boolean isMatch = m.matches();
            if (!isMatch) {
                ToastUtil.showShort(StageBaoApplication.getInstance(), "请填入正确的手机号");
            }
            return isMatch;
        }
    }


    /**
     * 设置RecyclerView子项间隔
     */
    public static class SpaceItemDecoration extends RecyclerView.ItemDecoration {

        private int leftRight;
        private int topBottom;

        //leftRight为横向间的距离 topBottom为纵向间距离
        public SpaceItemDecoration(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }


    }


    /**
     * 设置RecyclerView子项间隔
     */
    public static class SpaceItemDecorationStaggered extends RecyclerView.ItemDecoration {

        private int leftRight;
        private int topBottom;

        //leftRight为横向间的距离 topBottom为纵向间距离
        public SpaceItemDecorationStaggered(int leftRight, int topBottom) {
            this.leftRight = leftRight;
            this.topBottom = topBottom;
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            super.onDraw(c, parent, state);
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            StaggeredGridLayoutManager layoutManager = (StaggeredGridLayoutManager) parent.getLayoutManager();
            //竖直方向的
            if (layoutManager.getOrientation() == LinearLayoutManager.VERTICAL) {
                //最后一项需要 bottom
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.bottom = topBottom;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.right = leftRight;
            } else {
                //最后一项需要right
                if (parent.getChildAdapterPosition(view) == layoutManager.getItemCount() - 1) {
                    outRect.right = leftRight;
                }
                outRect.top = topBottom;
                outRect.left = leftRight;
                outRect.bottom = topBottom;
            }
        }


    }


    /**
     * 返回需要的请求参数
     *
     * @param param
     * @return
     */
    public static Map<String, Map<String, String>> returnRealParam(Map<String, String> param) {
        Map<String, String> header = new HashMap<>();
        header.put("token", Util.Token);
        header.put("mode", "Android");
//        TelephonyManager tm = (TelephonyManager) StageBaoApplication.getInstance()
//                .getSystemService(Context.TELEPHONY_SERVICE);
//        String DEVICE_ID = tm.getDeviceId();
//        header.put("device", DEVICE_ID);//设备号

        header.put("device", DeviceUtil.getDeviceId(StageBaoApplication.getmContext()));//设备号
//        PackageManager manager = StageBaoApplication.getInstance().getPackageManager();
//        PackageInfo info = null;
//        try {
//            info = manager.getPackageInfo(StageBaoApplication.getInstance().getPackageName(), 0);
//        } catch (PackageManager.NameNotFoundException e) {
//            e.printStackTrace();
//        }
//        header.put("version", info.versionCode + "");//版本信息
        header.put("version", DeviceUtil.getVersionCode(StageBaoApplication.getmContext()));//版本信息
        header.put("uid", Util.UserId);

        Map<String, Map<String, String>> realParam = new HashMap<>();
        realParam.put("header", header);
        realParam.put("param", param);
        return realParam;
    }


    /**
     * 设置Tablayout的下划线长度
     *
     * @param tabs
     * @param leftDip
     * @param rightDip
     */
    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());

        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }


    }


    public static void doBlur(final ImageView imageView) {
        imageView.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {

            @Override
            public boolean onPreDraw() {
                imageView.getViewTreeObserver().removeOnPreDrawListener(this);
                imageView.buildDrawingCache();
                Bitmap bmp = imageView.getDrawingCache();
                blur(getContext(), bmp, imageView);
                return true;
            }
        });
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    private static void blur(Context context, Bitmap bkg, View view) {
        long startMs = System.currentTimeMillis();
        float radius = 20;

        Bitmap overlay = Bitmap.createBitmap((int) (view.getMeasuredWidth()), (int) (view.getMeasuredHeight()), Bitmap.Config.ARGB_4444);
        Canvas canvas = new Canvas(overlay);
        canvas.translate(-view.getLeft(), -view.getTop());
        canvas.drawBitmap(bkg, 0, 0, null);

        RenderScript rs = RenderScript.create(context);

        Allocation overlayAlloc = Allocation.createFromBitmap(rs, overlay);
        ScriptIntrinsicBlur blur = ScriptIntrinsicBlur.create(rs, overlayAlloc.getElement());
        blur.setInput(overlayAlloc);
        blur.setRadius(radius);
        blur.forEach(overlayAlloc);
        overlayAlloc.copyTo(overlay);
        view.setBackground(new BitmapDrawable(context.getResources(), overlay));
        rs.destroy();
    }
}
